import {createRouter, createWebHistory} from 'vue-router'
import {getToken} from "@/utils/cookie.js";
import {ElMessage} from "element-plus";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: "/",
            redirect: '/oj/login',
        },
        {
            path: '/oj/login',
            name: 'login',
            component: () => import('@/views/Login.vue')
        },
        {
            path: '/oj/layout',
            name: 'layout',
            component: () => import('@/views/Layout.vue'),
            redirect: '/oj/layout/question',
            children: [
                // 二级路由, 默认跳转到 question
                {
                    path: 'cuser',
                    name: 'cuser',
                    component: () => import('@/views/Cuser.vue')
                },
                {
                    path: 'exam',
                    name: 'exam',
                    component: () => import('@/views/Exam.vue')
                },
                {
                    path: 'question',
                    name: 'question',
                    component: () => import('@/views/Question.vue')
                },
                {
                    path: 'updateExam',
                    name: 'updateExam',
                    component: () => import('@/views/UpdateExam.vue')
                }
            ]
        },
    ],
})


// 路由守卫
router.beforeEach((to, from, next) => {
    // to 表示将要访问的路径, from 表示从哪个路径跳转而来, next 是一个函数，表示放行
    if (getToken()) {  //已经登陆过
        /* has token*/
        if (to.path === '/oj/login') {
            next({ path: '/oj/layout/question' })
        } else {
            next()
        }
    } else {
        if (to.path !== '/oj/login') {
            ElMessage.error('未登录，请先登录')
            next({path:'/oj/login'})
        } else {
            next()
        }
    }
})


export default router
